import axios from 'axios'
import {Message} from 'iview'
import store from '@/store'
import router from '@/router'

class HttpRequest {
  constructor(baseUrl = baseURL) {
    this.baseUrl = baseUrl
    this.queue = {}
  }

  getInsideConfig() {
    const config = {
      baseURL: this.baseUrl,
      headers: {
        //
      }
    }
    return config
  }

  destroy(url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) {
      // Spin.hide()
    }
  }

  interceptors(instance, url) {
    // 请求拦截
    instance.interceptors.request.use(config => {
      // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
      config.headers['token'] = sessionStorage.getItem('token')
      config.url = "/api/" + config.url
      // 添加全局的loading...
      if (!Object.keys(this.queue).length) {
        // Spin.show() // 不建议开启，因为界面不友好
      }
      this.queue[url] = true
      return config
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      this.destroy(url)
      if (res.status === 200) {
        if (res.data.code === '0') {
          return res.data;
        } else if (res.data.code === '-1') {
          Message.error(res.data.msg)
        }
      }
      const {data, status} = res
      return {data, status}
    }, error => {
      if (error.response) {
        console.log(error.response)
        switch (error.response.status) {
          case 401:
            // 返回 401 清除token信息并跳转到登录页面
            store.commit('setRedis', "")
            store.commit('setToken', '')
            store.commit('setMsgData', [])
            store.commit('setAccess', [])
            store.commit('setHasGetInfo', false)
            sessionStorage.clear()
            router.replace({
              path: '/login'
            })
            Message.error("token已失效！")
            break;
        }
      }
      this.destroy(url)
      // addErrorLog(error.response)
      return Promise.reject(error)
    })
  }

  request(options) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }
}

export default HttpRequest
